<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>三级联动</title>
  </head>
  <body>
    <select name="省份" id="province">
      <option value="">省份</option>
    </select>
    <select name="城市" id="city">
      <option value="">城市</option>
    </select>
    <select name="区县" id="area">
      <option value="">区县</option>
    </select>

    <script>
      let province = document.querySelector("#province");
      let city = document.querySelector("#city");
      let area = document.querySelector("#area");

      fetch("./city.json")
        .then(function (response) {
          return response.json();
        })
        .then(function (data) {
          console.log(data);

          //省
          for (let key in data) {
            province.innerHTML += `<option value="${key}">${key}</option>`;
          }

          //市
          province.addEventListener("change", function () {
            city.innerHTML = `<option value="">城市</option>`;
            area.innerHTML = `<option value="">区县</option>`;
            for (let key in data) {
              // console.log(data[key]);
              if (key == province.value) {
                for (let key1 in data[key]) {
                  city.innerHTML += `<option value="${key1}">${key1}</option>`;
                }
              }
            }
          });

          //区县
          city.addEventListener("change", function () {
            area.innerHTML = `<option value="">区县</option>`;
            for (let key in data) {
              if (key == province.value) {
                for (let key1 in data[key]) {
                  if (key1 == city.value) {
                    for (let key2 in data[key][key1]) {
                      area.innerHTML += `<option value="${data[key][key1][key2]}">${data[key][key1][key2]}</option>`;
                    }
                  }
                }
              }
            }
          });
        })
        .catch(function (error) {
          console.log(error);
        });
    </script>
  </body>
</html>
